package me.zhengjie.config.redis;

import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.databind.ObjectMapper; // 修复导入
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import me.zhengjie.webuser.util.AvatarResource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@ConditionalOnClass(RedisOperations.class)
public class SystemRedisConfig {

    /**
     * 专用于 AvatarResource 的 RedisTemplate
     */
    @Bean(name = "avatarRedisTemplate")
    public RedisTemplate<String, AvatarResource> avatarRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, AvatarResource> template = new RedisTemplate<>();
        configureJacksonSerializer(template, redisConnectionFactory);
        return template;
    }

    /**
     * 配置 Jackson 序列化策略
     */
    private void configureJacksonSerializer(RedisTemplate<String, AvatarResource> template,
                                            RedisConnectionFactory factory) {
        Jackson2JsonRedisSerializer<AvatarResource> serializer =
                new Jackson2JsonRedisSerializer<>(AvatarResource.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.addMixIn(Resource.class, ResourceMixin.class); // 处理 Resource 字段
        serializer.setObjectMapper(objectMapper);

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
    }

    /**
     * 忽略 Resource 类型的序列化
     */
    @JsonIgnoreType
    private static abstract class ResourceMixin {}
}